using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Threading;

namespace RStein.Posterous.API
{
    internal class SimpleWebFactory
    {
        #region events
        public event EventHandler<EventArgsValue<IRawRequestResponsePublisher>> WebObjectCreated;
        #endregion events
        #region private fields
        private Dictionary<Type, Func<object>> m_types;
        #endregion private fiels
        
        #region constructors
        private SimpleWebFactory()
        {
          m_types = new Dictionary<Type, Func<Object>>();
          setupDefaultTypes();
        }

        

        #endregion constructors
        #region methods
        public void RegisterType<T>(Func<Object> creator)
                                where T : class
        {
           if (creator == null)
           {
               throw new ArgumentNullException("creator");
           }
            m_types.Add(typeof(T), creator);
        }
        
        public T Create<T>() where T : class
        {
            Func<Object> creator;
            m_types.TryGetValue(typeof (T), out creator);
            if(creator == null)
            {
                throw new Exception(GlobalConstants.MISSING_TYPE_EX);
            }

            Object retObject = creator();
            IRawRequestResponsePublisher publisher =  retObject as IRawRequestResponsePublisher;
            
            if (publisher != null)
            {
                OnWebObjectCreated(new EventArgsValue<IRawRequestResponsePublisher>(publisher, null));    
            }
            
            return retObject as T;

        }
        protected virtual void OnWebObjectCreated(EventArgsValue<IRawRequestResponsePublisher> e)
        {
            EventHandler<EventArgsValue<IRawRequestResponsePublisher>> handler = WebObjectCreated;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        private void setupDefaultTypes()
        {
            RegisterType<ISimpleDownloader>(() => new SimpleDownloader());
            RegisterType<IPosterousRequestBuilder>(() => new PosterousRequestBuilder());
            
            #if SILVERLIGHT
            RegisterType<IWebClient>(() => new SLWebClientEx());
            #else
            RegisterType<IWebClient>(() => new WebClientEx());
            #endif 

        }
        #endregion methods
        

        
        public static SimpleWebFactory Instance
        {
            get
            {
                return SimpleWebFactoryCreator.WebFactoryInstance;
            }
        }

        private class SimpleWebFactoryCreator
        {
            public static SimpleWebFactory WebFactoryInstance = new SimpleWebFactory();
        }
    }
}